package com.gexin.common.utils.email;

//import com.gexin.model.Email.EmailInfo;
import com.gexin.common.utils.StringUtil;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class EmailUtil {
	private static Log log = Log.getLog(EmailUtil.class);
	public static MailAuthenticator authenticator;
	private static MimeMessage message;
	private static Session session;
	private static Transport transport;
	private static Properties properties = new Properties();

	private static String mailHost = PropKit.get("mailHost");
	private static String sender_username = PropKit.get("mailUserName");
	private static String sender_password = PropKit.get("mailPassword");

	/**合同个人 路径*/
	public static final String dealerIindividual = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"/doc/gr.pdf";
	/**合同二级 路径*/
	public static final String dealerLevelTwo = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"/doc/ej.pdf";
	/**合同区域 路径*/
	public static final String ResellerRegionalEdition = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"/doc/qy.pdf";

	// 初始化smtp发送邮件所需参数
	static{
//		properties.put("mail.smtp.host", mailHost);// mail.envisioncitrix.com
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.transport.protocol", "smtp");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.ssl.checkserveridentity", "false");
//		properties.put("mail.smtp.ssl.trust", mailHost);
		authenticator = new MailAuthenticator(sender_username, sender_password);
		session = Session.getInstance(properties, authenticator);
		session.setDebug(false);// 开启后有调试信息
		message = new MimeMessage(session);
	}


	/**
	 * 供外界调用的发送邮件接口
	 */
	public static boolean sendEmail(String title, String content, List<String> receivers, List<File> fileList) {
		try {
			// 初始化smtp发送邮件所需参数
//			initSmtpParams();
			// 发送邮件
			doSendHtmlEmail(title, content, receivers, fileList);

		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return true;
	}

	/**
	 * 初始化smtp发送邮件所需参数
	 */
	private boolean initSmtpParams() {

		properties.put("mail.smtp.host", mailHost);// mail.envisioncitrix.com
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.transport.protocol", "smtp");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.ssl.checkserveridentity", "false");
		properties.put("mail.smtp.ssl.trust", mailHost);

		authenticator = new MailAuthenticator(sender_username, sender_password);
		session = Session.getInstance(properties, authenticator);
		session.setDebug(false);// 开启后有调试信息
		message = new MimeMessage(session);
		return true;
	}

	/**
	 * 发送邮件
	 */
	private static boolean doSendHtmlEmail(String title , String htmlContent , List<String> receivers , List<File> fileList) {
		try {
			// 发件人
			InternetAddress from = new InternetAddress(sender_username);
			message.setFrom(from);

			// 收件人(多个)
			InternetAddress[] sendTo = new InternetAddress[receivers.size()];
			for (int i = 0; i < receivers.size(); i++) {
				sendTo[i] = new InternetAddress(receivers.get(i));
			}
			message.setRecipients(MimeMessage.RecipientType.TO, sendTo);

			// 邮件主题
			message.setSubject(title);

			// 添加邮件的各个部分内容，包括文本内容和附件
			Multipart multipart = new MimeMultipart();
			// 添加邮件正文
			BodyPart contentPart = new MimeBodyPart();
			contentPart.setContent(htmlContent, "text/html;charset=UTF-8");
			multipart.addBodyPart(contentPart);

			// 遍历添加附件
			if (fileList != null && fileList.size() > 0) {
				for (File file : fileList) {
					BodyPart attachmentBodyPart = new MimeBodyPart();
					DataSource source = new FileDataSource(file);
					attachmentBodyPart.setDataHandler(new DataHandler(source));
					attachmentBodyPart.setFileName(MimeUtility.encodeText(file.getName()));
					multipart.addBodyPart(attachmentBodyPart);
				}
			}

			// 将多媒体对象放到message中
			message.setContent(multipart);
			// 保存邮件
			message.saveChanges();
			// SMTP验证，就是你用来发邮件的邮箱用户名密码
			transport = session.getTransport("smtp");
			transport.connect(mailHost, sender_username, sender_password);

			// 发送邮件
			transport.sendMessage(message, message.getAllRecipients());

			System.out.println(title + " Email send success!");
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (transport != null) {
				try {
					transport.close();
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}



	public static void main(String[] args) {

		// 邮件主题
		String title = "测试发送邮件标题";

		// 邮件正文
		String htmlContent = "测试发送邮件内容";

		// 收件人
		List<String> receivers = new ArrayList<String>();
//		receivers.add("523106472@qq.com");
		receivers.add("yue55663057@163.com");

		// 附件
		URL resource = Thread.currentThread().getContextClassLoader().getResource("");
		System.out.println(resource);
		String fileName1 = "doc/经销商-个人.docx";

		File file1 = new File(fileName1);
//		String fileName2 = "附件路径2";
//		File file2 = new File(fileName2);
		List<File> fileList = new ArrayList<File>();
		fileList.add(file1);
//		fileList.add(file2);
		System.out.println(file1);
		// 执行发送
		sendEmail(title, htmlContent, receivers, fileList);
	}

}
